using System;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace WebUI.HtmlHelpers
{
    public static class CalendarHelper
    {
        public static string Calendar(this HtmlHelper helper, DateTime dateToShow)
        {
            var cinfo = DateTimeFormatInfo.CurrentInfo;
            var sb = new StringBuilder();
            var date = new DateTime(dateToShow.Year, dateToShow.Month, 1);
            var daysPrevMonth = date;
            
            var emptyCells = ((int)date.DayOfWeek + 7 - (int)cinfo.FirstDayOfWeek) % 7;
            var days = DateTime.DaysInMonth(dateToShow.Year, dateToShow.Month);
            sb.Append("<table class='calendar'>");

            var skipDay = GetStartDayOfMonth(days, emptyCells);

            daysPrevMonth = daysPrevMonth.AddDays(-skipDay);
            
            
            for (int i = 0; i < ((days + emptyCells) > 35 ? 42 : 35); i++)
            {
                if (i % 7 == 0)
                {
                    if (i > 0) sb.Append("</tr>");
                    sb.Append("<tr>");
                }

                if (i < emptyCells || i >= emptyCells + days)
                {

                    if (i >= emptyCells + days)
                    {
                        sb.Append("<td class='cal-empty'> * </td>");
                    }
                    else
                    {
                        sb.Append("<td class='cal-empty'>" + daysPrevMonth.Day + "</td>");
                        daysPrevMonth = daysPrevMonth.AddDays(1);
                    }
                }

                else
                {
                    sb.Append("<td class='cal-day'>" + date.Day + "</td>");
                    date = date.AddDays(1);
                }
            }
            sb.Append("</table>");
            return sb.ToString();
        }

        private static int GetStartDayOfMonth(int days, int emptyCells)
        {
            var result = 0;
            for (int i = 0; i < ((days + emptyCells) > 35 ? 42 : 35); i++)
            {
                if (i < emptyCells)
                {
                    result++;
                }
            }
            return result;
        }
    }
}